import time
import os
import shutil

class fileHandler:
    """Handler for the open files."""
    
    def __init__(self, fileno, username, filename):
        self.fileno = fileno
        self.filename = filename
        self.username = username
        
        # vector[line] = [["content", "user"]]
        self.contents = []
        
        self.lastAccess = time.time()
        self._read_file()
    
    def _read_file(self):
        #TODO currently if the file does not exist, this will cause an error
        
        folderPath = self.username + "\\" + self.filename + "\\"
        listing = os.listdir(folderPath)
        self.latest = 1
        for filename in listing:
            try:
                vers = int(filename)
                if self.latest < vers:
                    self.latest = vers
            except ValueError:
                pass
        
        filepath = folderPath + str(self.latest)
        self.fd = open(filepath, "a+")
        # cut the last character from each line, namely '\n'
        self.contents = []
        for line in self.fd.readlines():
            if (line[-1] == "\n"):
                self.contents.append([line[:-1], ""])
            else:
                self.contents.append([line, ""])
        
        if (len(self.contents) == 0):
            self.contents.insert(0, [ "", "" ])
        #self.contents = [[s[:-1], ""] for s in self.fd.readlines()]
        #print self.contents
    
    def save_contents(self):
        self.lastAccess = time.time()
        
        self.fd.close()
        
        folderPath = self.username + "\\" + self.filename + "\\"
        self.latest += 1
        filepath = folderPath + str(self.latest)
        self.fd = open(filepath, "w")
        self.fd.truncate()
        
        for line in self.contents:
            self.fd.write(line[0] + "\n")
        self.fd.flush()
    
    def restore_vers(self, vers):
        if (int(vers) > self.latest):
            return False
        self.lastAccess = time.time()
        
        self.fd.close()
        
        folderPath = self.username + "\\" + self.filename + "\\"
        self.latest += 1
        filepathd = folderPath + str(self.latest)
        filepaths = folderPath + vers
        
        shutil.copyfile(filepaths, filepathd)
        self._read_file()
        return True
        
    
    def get_contents(self):
        self.lastAccess = time.time()
        return [x[0] for x in self.contents]
    
    def get_line(self, line):
        self.lastAccess = time.time()
        return self.contents[line][0]
    
    def update_line(self, line, uname, txt):
        self.lastAccess = time.time()
        if (self.contents[line][1] != uname):
            return
        self.contents[line][0] = txt
    
    def new_line(self, lineNr, offset, uname):
        for item in self.contents:
            if item[1] == uname:
                item[1] = ""
        newCont = self.contents[lineNr][0][offset:]
        self.contents[lineNr][0] = self.contents[lineNr][0][0:offset]
        self.contents.insert(lineNr+1, [newCont, uname])
        
    def del_line(self, line, username):
        if (line <= 0):
            return True
        if (line > len(self.contents)):
            return False
        if (self.contents[line][1] != username):
            return False
        if (self.isLineFree(line-1) == False):
            return False
        self.contents[line-1][1] = username
        self.contents[line-1][0] += self.contents[line][0]
        del self.contents[line]
        return True
    
    def get_usrs(self):
        """Returns a list of [usr, line]"""
        ret = []
        
        for line, item in enumerate(self.contents):
            if (self.isLineFree(line)):
                continue
            ret.append([item[1], line])
        
        return ret
        
    def ocupy(self, line, user):
        for item in self.contents:
            if item[1] == user:
                item[1] = ""
                break
        
        if (line == len(self.contents)):
            self.contents.insert(line, ["", user])
            return True
        
        if self.isLineFree(line):
            self.contents[line][1] = user
            return True
        print "Line " + str(line) + " oc by " + self.contents[line][1] 
        return False
    
    def free(self, line):
        self.lastAccess = time.time()
        self.contents[line][1] = ""
    
    def isLineFree(self, line):
        self.lastAccess = time.time()
        return self.contents[line][1] == ""
    
    def getUserOcupiedLine(self, user):
        self.lastAccess = time.time()
        for line, item in enumerate(self.contents):
            if item[1] == user:
                return line
        return -1
    
    def check(self):
        self.lastAccess = time.time()
    
    def __str__(self):
        return "%d %s" % ( self.fileno, self.contents)
    
    def __repr__(self):
        return self.__str__()

if __name__ == "__main__":
    os.chdir("..\\files\\")
    f = fileHandler(3, "sam", "test3")
    print f.get_contents()
    f.ocupy(1, "sam")
    f.del_line(1, "sam")
    print f.get_contents()

    
    
